package com.atguigu.chapter07.D01_Window;

import com.atguigu.bean.WaterSensor;
import com.atguigu.util.AnqclnUtil;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * Author: Pepsi
 * Date: 2023/8/4
 * Desc:
 *
 * 窗口内的元素进行处理，用到窗口处理函数，分两大类：
 *
 * 增量处理
 *      简单聚合
 *          sum  max  min
 *          maxBy  minBy
 *      reduce
 *          输入和输出类型必须一致
 *      aggregate
 *          可以不一致，中间有累加器做转换
 *
 * 全量处理
 *      process
 *
 *
 */
public class Flink04_Window_Aggregate_Process {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 1000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);

        env
                .socketTextStream("hadoop101", 9999)
                .map(line -> {
                    String[] data = line.split(",");

                    return new WaterSensor(
                            data[0],
                            Long.valueOf(data[1]),
                            Integer.valueOf(data[2])
                    );
                })
                .keyBy(WaterSensor::getId)
                .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                .aggregate(new AggregateFunction<WaterSensor, Avg , Double>() {
                    // 初始化一个累加器
                    // 每个窗口执行一次
                    @Override
                    public Avg createAccumulator() {
                        System.out.println("createAccumulator 执行了...");
                        return  new Avg();
                    }
                    // 累加方法
                    // 每来一个元素执行一次
                    @Override
                    public Avg add(WaterSensor value, Avg accumulator) {
                        System.out.println("add 执行了...");
                        accumulator.sum += value.getVc();
                        accumulator.count++;
                        return accumulator;
                    }
                    // 返回最终的聚合结果
                    // 每个窗口执行一次
                    @Override
                    public Double getResult(Avg accumulator) {
                        System.out.println("getResult 执行了...");
                        return accumulator.sum * 1.0 / accumulator.count;
                    }
                    // 合并累加器
                    // 注意：这个方法只在session窗口会调用，其他窗口不执行
                    @Override
                    public Avg merge(Avg a, Avg b) {
                        return null;
                    }
                })
                .print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class Avg{
        public Integer sum = 0;
        public Long count = 0L;
    }
}